﻿using System.Reflection;

using BodaNetCommunications.CommBase.Interfaces;

using BodaNetCommunications.Utilities.ComTypes;

namespace BodaNetCommunications.McComs.McComsUtil
{
    internal class McHelper
    {
        public static (McAddressArea, string) McTranferAddress(string address)
        {
            var addressTransferTypes = Assembly.GetExecutingAssembly().GetTypes()
                  .Where(m => typeof(IAddressTransfer).IsAssignableFrom(m)
                                  && m.GetCustomAttribute<McPlcAttribute>() != null
                                  && McPLCType.McPlc == m.GetCustomAttribute<McPlcAttribute>()?.PlcType);

            if (addressTransferTypes == null || addressTransferTypes.Count() > 1)
            {
                throw new Exception("未获取到数据转换的IAddressTransfer接口，或者有多个转换接口");
            }

            var addressTransferType = addressTransferTypes.First();
            IAddressTransfer? addressTransfer = Activator.CreateInstance(addressTransferType) as IAddressTransfer;
            var res = addressTransfer?.TransferAddress(address) ?? throw new Exception("地址转换失败");
            return res;
        }
    }
}
